'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller {
  async add() {
    const { ctx } = this;
    const rule = {
      roleId: { type: 'number' },
      username: { type: 'string' },
      realName: { type: 'string' },
    };
    try {
      ctx.validate(rule, ctx.request.body);
      ctx.body = await ctx.service.user.add(ctx.request.body);
    } catch (e) {
      ctx.body = ctx.helper.paramError(e);
    }
  }

  async find() {
    const { ctx } = this;
    const { pageString } = ctx.helper;
    const { id } = ctx.request.query;
    const rule = { id: pageString() };
    try {
      ctx.validate(rule, ctx.request.query);
      ctx.body = await ctx.service.user.find(parseInt(id));
    } catch (e) {
      ctx.body = ctx.helper.paramError(e);
    }
  }

  async update() {
    const { ctx } = this;
    const rule = {
      id: { type: 'number' },
      username: { type: 'string' },
      realName: { type: 'string' },
    };
    try {
      ctx.validate(rule, ctx.request.body);
      ctx.body = await ctx.service.user.update(ctx.request.body);
    } catch (e) {
      ctx.body = ctx.helper.paramError(e);
    }
  }

  async delete() {
    const { ctx } = this;
    const rule = { id: { type: 'number' } };
    try {
      ctx.validate(rule, ctx.request.body);
      ctx.body = await ctx.service.user.delete(ctx.request.body.id);
    } catch (e) {
      ctx.body = ctx.helper.paramError(e);
    }
  }

  async list() {
    const { ctx } = this;
    const { pageString } = ctx.helper;
    const { current, pageSize } = ctx.request.query;
    const rule = {
      current: pageString(),
      pageSize: pageString(),
    };
    try {
      ctx.validate(rule, { current, pageSize });
      ctx.body = await ctx.service.user.list(parseInt(current), parseInt(pageSize));
    } catch (e) {
      ctx.body = ctx.helper.paramError(e);
    }
  }
}

module.exports = UserController;
